Page({
  data: {
    idcardFrontUrl: '/static/images/avatar_1.jpg',
    idcardBackUrl: '/static/images/avatar_2.jpg',
    name: '',
    gender: 1,
    mobile: ''
  },
  onLoad({ point, building, room, id }) {
    if (id) {
      wx.setNavigationBarTitle({
        title: '编辑房屋信息'
      })
      this.detailRoom(id)
    } else {
      //添加房屋
      this.setData({
        point, building, room
      })
    }
  },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark.type
    this.setData({ [type]: '' })
  },
  //校验姓名
  checkName() {
    const reg = /^(?:[\u4e00-\u9fa5·]{2,16})$/
    const vaild = reg.test(this.data.name.trim())
    if (!vaild) wx.utils.toast('请输入2~16位中文姓名')
    return vaild
  },
  //校验手机号
  checkMobile() {
    const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
    const vaild = reg.test(this.data.mobile.trim())
    if (!vaild) wx.utils.toast('请输入合法的手机号码')
    return vaild
  },
  //校验身份证
  checkIdcard() {
    const vaild = this.data.idcardFrontUrl && this.data.idcardBackUrl
    if (!vaild) wx.utils.toast('请选择身份证正反面')
    return vaild
  },
  //提交审核
  async submit() {
    //校验姓名手机号码合法性身份证合法性
    if (!this.checkName()) return
    if (!this.checkMobile()) return
    if (!this.checkIdcard()) return
    delete this.data.__webviewId__
    delete this.data.status
    await wx.http.post('/room', this.data)
    wx.utils.toast(this.data.id ? '编辑房屋成功' : '添加房屋成功')
    wx.navigateBack({
      delta: this.data.id ? 2 : 4
    })
  },
  async chooseImg(e) {
    const type = e.mark.type
    console.log(type);
    //选择图片
    const res = await wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sizeType: ['compressed']
    })
    //上传图片
    wx.uploadFile({
      url: 'https://live-api.itheima.net/upload',
      filePath: res.tempFiles[0].tempFilePath,
      name: 'file',
      header: { Authorization: `Bearer ${getApp().token}` },
      success: (res) => {
        const data = JSON.parse(res.data)
        this.setData({
          [type]: data.data.url
        })
      }
    })

  },
  //获取房屋详情
  async detailRoom(id) {
    const res = await wx.http.get(`/room/${id}`)
    this.setData({
      ...res.data
    })
  },
})
